package com.xjscrm.console.chat.core.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.console.chat.core.ChatBaseMsgHandler;
import com.xjscrm.console.chat.enums.ChatMsgType;
import com.xjscrm.console.chat.frame.dto.ChatRecordDTO;
import com.xjscrm.console.chat.frame.dto.ChatSessionDTO;
import com.xjscrm.console.chat.frame.recv.RPullSessionMsg;
import com.xjscrm.console.chat.frame.send.SPullSessionResultMsg;
import com.xjscrm.console.chat.frame.send.SResultMsg;
import com.xjscrm.console.dto.chat.ChatTalkRecordQueryDTO;
import com.xjscrm.console.entity.ChatTalkRecord;
import com.xjscrm.console.entity.ChatTalkSession;
import com.xjscrm.console.entity.ChatTalkSessionStaffRel;
import com.xjscrm.console.service.customer.chat.ChatTalkRecordService;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionService;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionStaffRelService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author mingyang.chen create in 2024/3/12 09:41
 */
@Component
@Slf4j
public class ChatPullSessionMsgHandler extends ChatBaseMsgHandler<RPullSessionMsg> {

    @Autowired
    private ChatTalkSessionService chatTalkSessionService;
    @Autowired
    private ChatTalkSessionStaffRelService chatTalkSessionStaffRelService;
    @Autowired
    private ChatTalkRecordService chatTalkRecordService;

    @Override
    public SResultMsg doHandle(RPullSessionMsg content, ChannelHandlerContext ctx) {

        SPullSessionResultMsg pullSessionResultMsg = new SPullSessionResultMsg();

        Page<ChatSessionDTO> result = new Page<>(content.getSize(), content.getCurrent());
        pullSessionResultMsg.setPage(result);

        try {
            Long merId = content.getMerId();
            Long deviceUniqueId = content.getDeviceUniqueId();
            if (Objects.nonNull(content.getSearchStaffId())) {
                List<ChatTalkSessionStaffRel> chatTalkSessionStaffRels = chatTalkSessionStaffRelService.listByStaffId(merId, content.getSearchStaffId());
                if (ObjectUtils.isNotEmpty(chatTalkSessionStaffRels)) {
                    List<Long> sessionIds = chatTalkSessionStaffRels.stream().map(ChatTalkSessionStaffRel::getTalkSessionId).distinct().collect(Collectors.toList());
                    content.setSessionIds(sessionIds);
                }
            }
            //
            Page<ChatTalkSession> sessionPage = chatTalkSessionService.page(merId, content);

            if (ObjectUtils.isEmpty(sessionPage.getRecords())) {
                return pullSessionResultMsg;
            }
            //
            List<Long> sessionIds = sessionPage.getRecords().stream().map(ChatTalkSession::getId).distinct().collect(Collectors.toList());

            // 查询机器人关联的回话
            List<ChatTalkSessionStaffRel> sessionStaffRelList = chatTalkSessionStaffRelService.listBySessionIds(content.getMerId(), content.getStaffId(), sessionIds);
            Map<Long, ChatTalkSessionStaffRel> collect = sessionStaffRelList.stream().collect(Collectors.toMap(ChatTalkSessionStaffRel::getTalkSessionId, Function.identity()));

            List<ChatSessionDTO> resultRecords = new ArrayList<>();
            for (ChatTalkSession record : sessionPage.getRecords()) {
                ChatSessionDTO chatSessionDTO = new ChatSessionDTO();
                BeanUtils.copyProperties(record, chatSessionDTO);

                if (collect.containsKey(record.getId())) {
                    chatSessionDTO.setChat(1);
                }
                resultRecords.add(chatSessionDTO);
            }

            result.setRecords(resultRecords);
        } catch (Exception e) {
            log.error("拉取机器人最近会话失败", e);
            throw new BusinessException("拉取机器人最近会话失败");
        }
        return pullSessionResultMsg;
    }

    @Override
    public boolean checkMsg(RPullSessionMsg baseMsg) {
        return super.checkMsg(baseMsg) || !Objects.nonNull(baseMsg.getDeviceUniqueId());
    }

    @Override
    public Class<RPullSessionMsg> msgClass() {
        return RPullSessionMsg.class;
    }

    @Override
    public ChatMsgType msgType() {
        return ChatMsgType.r_pull_all_session;
    }

    private ChatRecordDTO doLoadTalkRecord(Long merId, Long lastTalkId) {
        ChatTalkRecordQueryDTO chatTalkRecordQuery = new ChatTalkRecordQueryDTO();
        chatTalkRecordQuery.setId(lastTalkId);
        chatTalkRecordQuery.setMerId(merId);
        ChatTalkRecord chatTalkRecord = chatTalkRecordService.loadLastTalk(chatTalkRecordQuery);
        if (Objects.isNull(chatTalkRecord)) {
            return null;
        }
        ChatRecordDTO chatRecordDTO = new ChatRecordDTO();
        BeanUtils.copyProperties(chatTalkRecord, chatRecordDTO);
        return chatRecordDTO;
    }
}
